/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.stip.server.da;

import com.stip.server.entities.UserToken;
import java.util.Date;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.*;

/**
 *
 * @author BlueBerry
 */
@Stateless
@LocalBean
public class UserTokenDA {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    EntityManager em;
    public String findToken(String token){
        if (token==null) {
            return  null;
        }
        if (em.find(UserToken.class, token)!=null) {
            return  em.find(UserToken.class, token).getUid();
        } else {
            return  null;
        }
      
    }
     
    public String addToken(String token,String uId ){
    UserToken userToken=new UserToken();
    
    userToken.setAccessDate(new Date());
    userToken.setAccessTakon(token);
    userToken.setUid(uId);
    em.persist(userToken);
        try {
            
            em.flush();
            return  userToken.getAccessTakon();
        } catch (EntityExistsException e) {
            return  null;
        }
    
    }
    public String editTokenByUID(String uid,String newToken){
    Query query=em.createNamedQuery("UserToken.findByUid");
        try {
           UserToken userToken= (UserToken)query.getSingleResult();
           userToken.setAccessTakon(newToken);
           userToken.setAccessDate(new Date());
           em.merge(userToken);
           return  userToken.getAccessTakon();
          
        } catch ( NoResultException e) {
            return  null;
        }
    
    }
    public String editToken(String NewToken,String Token){
    UserToken userToken=em.find(UserToken.class, Token);
        if (userToken!=null) {
    userToken.setAccessDate(new Date());
    userToken.setAccessTakon(NewToken);
    em.merge(userToken);
    em.flush();
    return userToken.getAccessTakon();
        } else {
            return  null;
        }

    
    
    }
}
